package com.gcxy.shop.controller;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.gcxy.shop.common.CommonException;
import com.gcxy.shop.domain.User;
import com.gcxy.shop.service.UserService;

@WebServlet(urlPatterns="/login.do")
public class LoginServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;
	private Logger logger=LoggerFactory.getLogger(getClass());
	private UserService userService=new UserService();
	
	
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	logger.debug("开始执行debug");
		try {
		     //抽取参数
			String usercode=request.getParameter("usercode");
			String password=request.getParameter("password");
			logger.debug("获取参数成功：{},{}",usercode,password);
	     
				//数据转换
				//数据判断
			if(usercode==null||usercode.length()<=4||password.length()<6) {
				throw new CommonException("账号和密码长度错误");
			}
			 logger.debug("校验成功");
				//业务处理
		        User user=userService.login(usercode,password);//登陆成功之后 返回user,一个user对象就表示数据库里面的一条记录
		        HttpSession session=request.getSession();//把user写到里面
				session.setAttribute("user",user);//把当前登陆的用户写到session里面去
		       logger.debug("业务处理成功");
			
				//转发与重定向
		       request.getRequestDispatcher("/index.jsp").forward(request, response);
			
	} catch (Exception e) {
		logger.error(e.getMessage());
		request.setAttribute("error",e.getMessage());
		request.getRequestDispatcher("/login.jsp").forward(request,response);
	}
		
	}
	
	
	
			
}
